#include <muduo/net/TcpServer.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/Buffer.h>
#include <muduo/net/InetAddress.h>
#include <iostream>
#include <unordered_map>

//实现翻译服务器
class Server
{
private:
    //连接的回调
    void onConnection(const muduo::net::TcpConnectionPtr& conn)//连接的对象
    {
        if(conn->connected())
        {
            std::cout<<"连接成功"<<std::endl;
        }
        else
        {
            std::cout<<"连接失败"<<std::endl;
        }
    }
    //消息的回调
    void onMessage(const muduo::net::TcpConnectionPtr & conn,muduo::net::Buffer * buf,muduo::Timestamp)//连接,缓冲区,时间
    {
        std::string msg = buf->retrieveAllAsString();//获取缓冲区中的数据(不考虑粘包问题)
        static std::unordered_map<std::string,std::string> dict_map = {{"key","关键"},{"world","世界"},{"hello","你好"}};
        std::unordered_map<std::string,std::string>::iterator iter = dict_map.find(msg);
        std::string res;
        if(iter != dict_map.end())
        {
            res = iter->second;
        }
        else
        {
            res = "未知单词";
        }
        conn->send(res);//typedef std::shared_ptr<TcpConnection> TcpConnectionPtr;
    }
public:
    Server(int port):_server(&_baseloop,muduo::net::InetAddress("0.0.0.0",port),"Dictserver",muduo::net::TcpServer::kReusePort)//启动地址重用
    {   
        //设置连接回调函数
        _server.setConnectionCallback(std::bind(&Server::onConnection,this,std::placeholders::_1));
        //设置消息回调函数
        _server.setMessageCallback(std::bind(&Server::onMessage,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
    }

    //启动服务器
    void Start()
    {
        //先开始监听
        _server.start();
        //再开始循环检测连接
        _baseloop.loop();
    }
    ~Server()
    {}
private:
    muduo::net::EventLoop _baseloop;//一定要放在_server前面
    //muduo库的TcpServer
    muduo::net::TcpServer _server;//  TcpServer(EventLoop* loop,const InetAddress& listenAddr,const string& nameArg,Option option = kNoReusePort);
};

int main()
{
    Server server(9090);
    server.Start();
}